package rest

import (
	"errors"

	pb "bilinadmin/api/pb/server"

	"github.com/labstack/echo/v4"

	"bilinadmin/internal/service"
	"bilinadmin/pkg/lueerror"
)

type vHandler struct {
	*Base
	name string
}

// NewRestVendorHandler 品牌 handler
func NewRestVendorHandler() *vHandler {
	return &vHandler{
		Base: base,
		name: "rest_vendor_handler",
	}
}

func (hl *vHandler) Register(r *echo.Group) {
	// 获取js api 参数
	r.GET("/v1/jsapi-params", hl.getJsApiParams)
	// 根据code 获取公众号授权
	r.GET("/v1/mp/auth", hl.getMpAuth)
	// 获取七牛上传 token
	r.POST("/v1/qiniu/upload-token", hl.getQiniuUploadToken)

	// 根据code 获取公众号授权
	r.GET("/v1/cos/bucketSets", hl.ListCosBucketSets)
	// 获取cos上传 authorization
	r.POST("/v1/cos/authorization", hl.getCosAuthorization)

}

func (e *vHandler) getJsApiParams(c echo.Context) error {
	ctx := c.Request().Context()
	url := c.QueryParam("url")
	if url == "" {
		return lueerror.InvalidRequest(errors.New("地址 不为空"))
	}
	ret, errL := service.GetVendorService().GetJsApiParam(ctx, url)
	return e.SimpleRet(c, ret, errL)
}

func (e *vHandler) getMpAuth(c echo.Context) error {
	ctx := c.Request().Context()
	code := c.QueryParam("code")
	if code == "" {
		return lueerror.InvalidRequest(errors.New("code 不为空"))
	}
	ret, errL := service.GetVendorService().OauthWechatMP(ctx, code)
	return e.SimpleRet(c, ret, errL)
}

func (e *vHandler) getQiniuUploadToken(c echo.Context) error {
	ctx := c.Request().Context()
	errL := e.VerifyAccountOrBilinToken(c)
	if errL != nil {
		return errL
	}
	req := &pb.GetQiniuUploadTokenReq{}
	if errL = e.ParseBody(c, req); errL != nil {
		return errL
	}
	ret := service.GetVendorService().GetQiniuUploadToken(ctx, req)
	return e.SimpleRet(c, ret, nil)
}

func (e *vHandler) ListCosBucketSets(c echo.Context) error {
	ctx := c.Request().Context()
	app := c.QueryParam("app")
	if app == "" {
		return lueerror.InvalidRequest(errors.New("app 不为空"))
	}
	ret, errL := service.GetVendorService().ListCosBucketSets(ctx, app)
	return e.SimpleRet(c, ret, errL)
}

func (e *vHandler) getCosAuthorization(c echo.Context) error {
	ctx := c.Request().Context()
	errL := e.VerifyAccountOrBilinToken(c)
	if errL != nil {
		return errL
	}
	req := &pb.GetCosAuthorizationReq{}
	if errL = e.ParseBody(c, req); errL != nil {
		return errL
	}

	ret, errL := service.GetVendorService().GetCosAuthorization(ctx, req)
	return e.SimpleRet(c, ret, errL)
}
